package com.info3k.client.components;

import java.util.List;

import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.info3k.client.Info3K;
import com.info3k.client.domain.Location;
import com.info3k.client.domain.User;

public class MyLocationList extends Composite {
	
	private VerticalPanel panel2 = new VerticalPanel();

	private Info3K info3k;
	
	private User user;
	
	private Pagination pagination = new Pagination(10);
	
	public MyLocationList(User user, Info3K info){
		this.info3k = info;
		this.user = user;
		VerticalPanel panel = new VerticalPanel();
		initWidget(panel);
		panel.setWidth("100%");
		panel.add(pagination);
		panel.add(new HTML("<div class=\"h_line\"></div>"));
		panel.setCellHorizontalAlignment(pagination, VerticalPanel.ALIGN_RIGHT);
		
		panel.add(panel2);
		panel.setCellWidth(panel2, "100%");
		panel2.setWidth("100%");
		callService(pagination.getPageSize(), null);
		
		pagination.addValueChangeHandler(new ValueChangeHandler<Integer>(){
			public void onValueChange(ValueChangeEvent<Integer> event) {
				callService(pagination.getPageSize(), event.getValue());
			}
		});
	}
	
	private void callService(Integer pageSize, Integer current){
		Info3K.loader.setVisible(true);
		Info3K.infoService.getLocationsByUser(user, pageSize, current, new AsyncCallback<List<Location>>(){
			public void onFailure(Throwable caught) {
				Info3K.loader.setVisible(false);
				InfoWindow.showMessage(Info3K.msgs.error(), caught.getMessage());
			}

			public void onSuccess(List<Location> result) {
				Info3K.loader.setVisible(false);
				if(result.size()>0 && result.get(0).getLength()!=null){
					pagination.setLength(result.get(0).getLength());
					pagination.render(0);
				}
				renderLocations(result);
			}
		});		
	}
	
	private void renderLocations(List<Location> locations){
		panel2.clear();
		for (Location location : locations) {
			LocationRenderer loc = new LocationRenderer(location, false, info3k);
			panel2.add(loc);
			panel2.add(new HTML("<hr>"));
		}
		if(locations.size()==0) panel2.add(new HTML(Info3K.msgs.noLocationsFound()));
	}
}
